package com.atguigu.dao;

import com.atguigu.domain.Permission;
import com.atguigu.domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RoleDao {
    //根据用户id查询出所有对应的角色
    @Select("select * from role where id in (select roleId from users_role where userId=#{userId})")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(select = "com.atguigu.dao.PermissionDao.findPermissionByRoleId"))
    })
    public List<Role> findRoleByUserId(String userId) throws Exception;

    @Select("select * from role")
    List<Role> findAl();

    @Insert("insert into role(roleName,roleDesc) values(#{roleName},#{roleDesc})")
    void save(Role role);

    @Select("select * from role where id=#{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions",column = "id",javaType = java.util.List.class,many = @Many(select = "com.atguigu.dao.PermissionDao.findPermissionByRoleId"))
    })
    Role findById(String id);

    @Delete("DELETE from role where id=#{roleId}")
    void deleteRole(String roleId);
    @Delete("DELETE from role_permission where roleId=#{roleId}")
    void deletepermissionRole(String roleId);
    @Delete("DELETE from users_role where roleId=#{roleId}")
    void deleteUsersRole(String roleId);

    @Select("select * from permission where id not in (SELECT permissionId from role_permission where roleId=#{id})")
    List<Permission> findOtherPermission(String id);

    @Insert("insert into role_permission(permissionId,roleId) values (#{permissionId},#{roleId});")
    void addPermissionToRole(@Param("roleId") String roleId,@Param("permissionId") String permissionId);
}
